package host.abetsy.recast.tools;

import org.newsclub.net.unix.AFUNIXSocket;
import org.newsclub.net.unix.AFUNIXSocketAddress;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class TrimMediaClient {

    // Unix socket 文件路径
    private static final String SOCKET_PATH = "/var/run/trim_media.sock";

    /**
     * 发送 HTTP 请求到 Unix domain socket
     */
    public static String sendRequest(String method, String path,
                                     Map<String, String> headers,
                                     String body) throws IOException {

        // 检查 socket 文件是否存在
        File socketFile = new File(SOCKET_PATH);
        if (!socketFile.exists()) {
            throw new IOException("Socket 文件不存在: " + SOCKET_PATH);
        }

        try (AFUNIXSocket socket = AFUNIXSocket.newInstance()) {
            // 设置超时时间（10秒）
            socket.setSoTimeout(10000);

            // 连接到 Unix socket
            socket.connect(AFUNIXSocketAddress.of(socketFile));

            // 构建 HTTP 请求
            StringBuilder requestBuilder = new StringBuilder();
            requestBuilder.append(method).append(" ").append(path).append(" HTTP/1.1\r\n");
            requestBuilder.append("Host: localhost\r\n");

            // 添加自定义请求头
            if (headers != null) {
                for (Map.Entry<String, String> header : headers.entrySet()) {
                    requestBuilder.append(header.getKey())
                            .append(": ")
                            .append(header.getValue())
                            .append("\r\n");
                }
            }

            // 如果有请求体，添加 Content-Length
            if (body != null && !body.isEmpty()) {
                requestBuilder.append("Content-Length: ")
                        .append(body.getBytes(StandardCharsets.UTF_8).length)
                        .append("\r\n");
            }
            // 结束请求头
            requestBuilder.append("Connection: close\r\n\r\n");
            // 添加请求体（如果有）
            if (body != null && !body.isEmpty()) {
                requestBuilder.append(body);
            }
            // 发送请求
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(requestBuilder.toString().getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            // 读取响应
            InputStream inputStream = socket.getInputStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line).append("\n");
            }
            return response.toString();
        }
    }

    /**
     * 发送 GET 请求
     */
    public static String get(String path) throws IOException {
        return get(path, null);
    }

    public static String get(String path, Map<String, String> headers) throws IOException {
        return sendRequest("GET", path, headers, null);
    }

    /**
     * 发送 POST 请求
     */
    public static String post(String path, String body) throws IOException {
        return post(path, null, body);
    }

    public static String post(String path, Map<String, String> headers, String body) throws IOException {
        return sendRequest("POST", path, headers, body);
    }

    /**
     * 主方法 - 使用示例
     */
    public static void main(String[] args) {
        try {
            // 示例 1: 简单的 GET 请求
            System.out.println("=== 发送 GET 请求 ===");
            String getResponse = get("/api/status");
            System.out.println("GET 响应:\n" + getResponse);

            // 示例 2: 带请求头的 GET 请求
            System.out.println("\n=== 发送带请求头的 GET 请求 ===");
            Map<String, String> headers = new HashMap<>();
            headers.put("User-Agent", "TrimMediaClient/1.0");
            headers.put("Accept", "application/json");

            String getResponseWithHeaders = get("/api/data", headers);
            System.out.println("带请求头的 GET 响应:\n" + getResponseWithHeaders);

            // 示例 3: POST 请求
            System.out.println("\n=== 发送 POST 请求 ===");
            String jsonBody = "{\"action\": \"trim\", \"start\": 0, \"end\": 100}";

            Map<String, String> postHeaders = new HashMap<>();
            postHeaders.put("Content-Type", "application/json");
            postHeaders.put("Accept", "application/json");

            String postResponse = post("/api/trim", postHeaders, jsonBody);
            System.out.println("POST 响应:\n" + postResponse);

        } catch (IOException e) {
            System.err.println("请求失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}